#include <esp_now.h>
#include <WiFi.h>

#define BUTTON_PIN 5  // GPIO5 for button input

typedef struct 
{
  uint8_t ledState;  // 1 = ON, 0 = OFF
} Data;

Data data;

uint8_t receiverMac[] = {0xE4, 0xB3, 0x23, 0xC4, 0x79, 0x88};  // Replace with your receiver's MAC

void OnDataSent(const uint8_t *mac, esp_now_send_status_t status) 
{
  Serial.print("Send Status: ");
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Success" : "Fail");
}

void setup() {
  Serial.begin(115200);

  pinMode(BUTTON_PIN, INPUT_PULLUP);  // Use pull-up resistor

  WiFi.mode(WIFI_STA);
  WiFi.setSleep(false);

  if (esp_now_init() != ESP_OK) {
    Serial.println("ESP-NOW init failed");
    return;
  }

  esp_now_register_send_cb(OnDataSent);

  esp_now_peer_info_t peerInfo = {};
  memcpy(peerInfo.peer_addr, receiverMac, 6);
  peerInfo.channel = 1;
  peerInfo.encrypt = false;
  peerInfo.ifidx = WIFI_IF_STA;

  if (!esp_now_is_peer_exist(receiverMac)) {
    if (esp_now_add_peer(&peerInfo) != ESP_OK) {
      Serial.println("Failed to add peer");
      return;
    }
  }
}

void loop() {
  data.ledState = digitalRead(BUTTON_PIN) == LOW ? 1 : 0;  // Active LOW button

  Serial.printf("Button State: %d\n", data.ledState);

  esp_err_t result = esp_now_send(receiverMac, (uint8_t *)&data, sizeof(data));

  if (result == ESP_OK) {
    Serial.println("Send Success");
  } else {
    Serial.println("Send Error");
  }

  delay(300);  // Debounce
}


